<?php
	$rootdir  = "/home/pcaban/checker/";// <<<< katalog glowny
	$innerdir = "dat/";// << podkatalog katalogu danego zadania na logi etc.
	$pdfdir   = ".pdf/";// << zadania
	$rozdir   = ".rozw/";// << katalog z przykladowymi rozwiazaniami
        $bindir   = ".dat/";// << pliki pomocnicze interfejsu internetowego
	
	$dirroot  = "/home/pcaban/checker/";//do katalogu /checker
	$dirzad   = $dirroot."zadania/"; //podkatalog z katalogami zadan
	
        $zalogowany = false;
	$badstrings = array("\"","'","^","_","?","\n","\r","\t","/","\\",":","*","|","<",">","$","&",";");
	    //stringi podmieniane przez funkcje GoodString
        $validurl = array("info.php","zadania.php","rozwiazania.php","upload.php","list.php","status.php",
            "ranking.php","logininterface.php","chpass.php","logout.php","admin.php","ranking_icm.php",
            "ranking_oi.php","logs.php","free.php","newaccount.php","ftp.php");
            //strony ktore mozna otworzyc


	function GoodString($str,$allowspacebars=true,$newstr="-")
	{//wywala niechciane stringi ze stringa
		global $badstrings;
		if(!$allowspacebars) $str=str_replace(" ","_",$str);
		foreach($badstrings as $i)
		{
		    $str=str_replace($i,$newstr,$str);
		}	    
		return $str;
        }

        function urlIsValid($url)
        {
            global $validurl;
            foreach($validurl as $valid)
                if(!strcmp($url, $valid)) return 1;
            return 0;
        }
	
	function PrintBannedStrings()
	{
	    global $badstrings;
	    print("&nbsp;&nbsp;<font size=2>Nie dopuszczamy stosowania w nazwach znakow: ");
	    foreach($badstrings as $i)
	    {
		print(" ".$i);
	    }
	    print(" (i kilku innych ;) )</font>");
	}

	function Data($timesign="")
	{//data w stosowanym przez nas formacie
	    if($timesign=="") return date("Y/m/d H:i:s");
	    else return date("Y/m/d H:i:s",$timesign);
	}
	
	function CzyAdmin($name="^")//nie zalezy w sumie od tego znaku... ale niech bedzie
	{
	    global $rootdir;
	    if($name=="^") $name=$_SESSION['user'];
	    if(file_exists($rootdir."admins.txt"))
	    {
		$file = fopen($rootdir."admins.txt","r");
		$ok=false;
		while(!feof($file))
		{
		    $s=fgets($file);
		    if($s==$name."\n")
		    {
			$ok=true;
			break;
		    }
		}
		fclose($file);
		if($ok) return true;
	    }
	    return false;
	}

	function DodajDoListy($src,$dir,$file,$text,$zad,$user)
	{
		global $rootdir,$dirroot;
                exec("lockfile -s1 -l3 ".$rootdir."rw.lock");
                //dodaj do kolejki
		if(file_exists($rootdir."kolejka.txt"))
		    $flist=fopen($rootdir."kolejka.txt","a");
		else 
                    $flist=fopen($rootdir."kolejka.txt","w");
                chmod($rootdir."kolejka.txt",0600);
		fwrite($flist, $src." ".$zad."\n");
		fclose($flist);
		//status ogolny
		if(file_exists($rootdir."status.txt"))
		    $lines = file($rootdir."status.txt");
		$flist=fopen($rootdir."status.txt","w");
		chmod($rootdir."status.txt",0600);
		fwrite($flist,$text."\n");
		fwrite($flist,Data()."\n");
		fwrite($flist,$user."\n");
		fwrite($flist,$zad."\n");
		fwrite($flist,"0\n");//status jako nie sprawdzony
		$cnt=0;
		$maxrecords=100;
		foreach($lines as $i)
		{
		    if(($cnt++)/5>=$maxrecords-1) break;
		    fwrite($flist,$i);
		}
		fclose($flist);
		//status osobisty
		if(!file_exists($dir))
		    mkdir($dir);
		$lines = array();
		if(file_exists($file))
		    $lines = file($file);
		$flist=fopen($file,"w");
		chmod($file,0600);
		fwrite($flist,$text."\n");
		fwrite($flist,Data()."\n");
		fwrite($flist,"0\n");//status jako nie sprawdzony
		foreach($lines as $i)
		{
		    fwrite($flist,$i);
		}
                fclose($flist);
                unlink($rootdir."rw.lock");
	}
	
	function DodajInfo($auth,$text)
	{
		global $bindir;
		$lines = array();
		if(file_exists($bindir."news.txt"))
		    $lines = file($bindir."news.txt");
		$flist=fopen($bindir."news.txt","w");
		fwrite($flist,Data()."\n");
		fwrite($flist,$text."\n");
		fwrite($flist,$auth."\n");
		foreach($lines as $i)
		{
		    fwrite($flist,$i);
		}
		fclose($flist);
	}
	
	function WyslijPlik($userfile1, $user, $zadanie)
	{//wysylanie pliku dla podanych parametrow
	    global $rootdir,$innerdir;
	    if(!$userfile1 || !$user || !$zadanie || $_FILES['userfile1']['size']==0)
	    {
		if($_FILES['userfile1']['size']==0) print("Plik nie moze byc pusty!");
		return;
	    }
	    do{
		$namenochars=$_FILES['userfile1']['name'];
		$namenochars=GoodString($namenochars,false,"-");
		$newname=$user."_".rand(0,1000000)."_".$namenochars;
	    }while(file_exists($rootdir.$newname) || file_exists($rootdir.$innerdir.$newname));
	    $uploaddir=$rootdir.$_POST['zadanie']."/";//gdzie wpakowac pliki
	    if(move_uploaded_file($_FILES['userfile1']['tmp_name'],$uploaddir.$newname))
	    {
		echo("Wysylanie pliku <b>".$_FILES['userfile1']['name']."</b> powiodlo sie!<br>");
		echo("<a href=\"index.php?page=list.php&zadanie=$zadanie\">Zobacz status</a><br>");
		chmod($uploaddir.$newname,0600);
		DodajDoListy($newname,$uploaddir.$innerdir,$uploaddir.$innerdir.$user.".txt",$newname,$_POST['zadanie'],$user);
		//exec($rootdir."test_run ".Date("Y/m/d:H:i:s")." &");
		exec("~/checker/run AUTO >>check.log 2>&1 &" );
	    }
	    else
	    {
		echo("Error sending file <b>".$_FILES['userfile1']['name']."<b>!<br>");
		print_r($_FILES);
	    }
	}

	function ListaZadan()
	{//wypisuje opcje bedace katalogami zadan dla <select>
	    global $rootdir;
	    $dir=opendir($rootdir);
	    while($file=readdir($dir))
	    {
		if(is_dir($rootdir.$file) && $file!="." && $file!=".." && $file!=".pdf" && $file!="bin" && $file!="in" && $file!="out" && $file[0]!='.')
		{
		    echo("<option value=\"".$file."\">".$file."</option>");
		}
	    }
	    closedir($dir);
	}

	//logowanie
	function Logout()
	{//obsluga wylogowania
	    session_start();    
	    session_destroy();
	    header("Location: index.php?page=info.php");
	}

        function CzyZalogowanyInit()
        {
            global $zalogowany;
            session_start();
            if($_SESSION['user']!="" && $_SESSION['user']!=null
                && $_SESSION['user']<1) $zalogowany=true;
            else
                $zalogowany=false;
        }
	function CzyZalogowany()
        {//czy jest zalogowany 
            global $zalogowany;
            return $zalogowany;
	}

	function Zalogowany()
	{//czy jest juz zalogowany jak nie to skok do panelu logowania
	    if(CzyZalogowany())
	    {
                $_POST['user']=$_SESSION['user'];
                return true;
	    }
	    else
	    {
                print("Zaloguj sie najpierw!<br>\n");
                return false;
	    }
	}
	
	function Status()
	{
	    print("zalogowany jako <b>".$_SESSION['user']."</b>".(CzyAdmin($_SESSION['user'])?" (administrator)":"")."<br>");
	    print("<a href=\"index.php?page=logout.php\">wyloguj</a><br>");
	}
	
	function Login()
	{//obsluga zapytania o zalogowanie
	    global $rootdir;
	    $user=$_POST['user'];
	    $passwd=$_POST['passwd'];
	    if($user && $passwd)
	    {
		$ok=false;
		$file=fopen($rootdir."users.txt","r");
		while(!feof($file))
		{
		    $name=fgets($file);
		    $pass=fgets($file);
		    //print("!$name|$pass<br>");
		    if($name==($user."\n") && md5($passwd)."\n"==$pass){
			$ok=true;
			break;
		    }
		}
		fclose($file);
		if($ok)
                {
		    session_start();
		    $_SESSION['user']=$user;
		    header("Location: index.php?info.php");
		}
		else
		{
		    //print("$user<br>$passwd<br>$name<br>$pass<br>".md5($passwd));    
		    header("Location: index.php?page=logininterface.php&bad=1");
		}
	    }
	}
	
	function LoginInterface()
	{//interfejs logowania
	    if($_GET['bad']==1)print("Zly login lub haslo!<br>");
	    print("<form enctype=\"multipart/form-data\" action=\"login.php\" method=\"post\">");
	    print("<table border=0>");
	    print("<tr><td>Nick:</td><td><input name=\"user\" type=\"text\"></td></tr>");
	    print("<tr><td>Haslo:</td><td><input name=\"passwd\" type=\"password\"></td></tr>");
	    print("<tr><td><input type=\"submit\" value=\"OK\"></td><td></td></tr>");
	    print("</table></form>");
	    print("Nie masz konta? <a href=\"index.php?page=newaccount.php\">Zaloz sobie</a>");
	}
	//koniec logowanie
	
	function InfoHeader($date="")
	{
	    if($date=="")$date=Data();
	    print("<table bgcolor=\"707070\" width=600px class=\"info\" border=0 bordercolor=black cellpadding=2 cellspacing=1>\n");
	    print("<tr bgcolor=\"#A0A0A0\"><td><b>".trim($date)."</b></td></tr>\n");
	}

        function HtmlFooter()
        {
            print("</td></tr>\n</table>\n</body>\n</html>\n");
        }

	function InfoMain($text)
	{
	    print("<tr bgcolor=\"E0E0E0\"><td>".trim($text)."</td></tr>\n");
	}
	
	function InfoFooter($author="")
	{
	    print("<tr bgcolor=\"#A0A0A0\"><td><b>autor: ".trim($author)."</b></td></tr>\n");
	    print("<table><br>\n");
	}

	function GetInfos(){
	    global $bindir;
	    $i=0;
	    if(file_exists($bindir."news.txt"))
	    {
		$file=fopen($bindir."news.txt","r");
		while(true){
		    $head=fgets($file);
		    $main=fgets($file);
		    $foot=fgets($file);
		    if(feof($file))break;
		    $i++;
		    InfoHeader($head);
		    InfoMain($main);
		    InfoFooter($foot);
		}
		fclose($file);
	    }
	    if(!$i) print("Chwilowo brak ogloszen...\n");
	}
	
?>
